#include <stdio.h>
#include "flash_rw.h"

//读写楼层信息*************************************
//uint32_t FlasFloorInfoAddr = 0x0801FC00; //信息保存地址，最后一页
uint8_t FLASH_FloorInfoLoad(uint8_t *id, uint16_t *lowlight, uint16_t *timeout)
{
    uint8_t flag = *(__IO uint8_t *)(FLASH_ADD);

    printf("flag :0x%x\r\n", flag);

    if (flag == SAVE_FLAG)
    {
        printf("flag is ok!\n");

        *id = *(__IO uint8_t *)(FLASH_ADD + 1);
        printf("read id = %d\n", *id);

        *lowlight = *(__IO uint16_t *)(FLASH_ADD + 2);
        printf("read lowlight = %d\n", *lowlight);

        *timeout = *(__IO uint16_t *)(FLASH_ADD + 4);
        printf("read timeout = %d\n", *timeout);
        return 1;
    }
    else
    {
        return 0;
    }
}

uint8_t FLASH_FloorInfoSave(uint8_t id, uint16_t lowlight, uint16_t timeout)
{

    FLASH_EraseInitTypeDef My_Flash; //声明 FLASH_EraseInitTypeDef 结构体为 My_Flash
    HAL_FLASH_Unlock();              //解锁Flash

    My_Flash.TypeErase = FLASH_TYPEERASE_PAGES; //标明Flash执行页面只做擦除操作
    My_Flash.PageAddress = FLASH_ADD;           //声明要擦除的地址
    My_Flash.NbPages = 1;                       //说明要擦除的页数，此参数必须是Min_Data = 1和Max_Data =(最大页数-初始页的值)之间的值

    uint32_t PageError = 0;                   //设置PageError,如果出现错误这个变量会被设置为出错的FLASH地址
    HAL_FLASHEx_Erase(&My_Flash, &PageError); //调用擦除函数擦除

    uint32_t Write_Flash_Data = SAVE_FLAG | id << 8 | lowlight << 16;

    HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, FLASH_ADD, Write_Flash_Data); //对Flash进行烧写，FLASH_TYPEPROGRAM_HALFWORD 声明操作的Flash地址的16位的，此外还有32位跟64位的操作，自行翻查HAL库的定义即可

    HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, FLASH_ADD + 4, timeout);

    HAL_FLASH_Lock(); //锁住Flash
    if (FLASH_ADD == PageError)
    {
        printf("seve=%d,Flash_ERR=%X\n", *(__IO uint16_t *)(FLASH_ADD), (unsigned int)(long)PageError);
        return 0;
    }

    return 1;
}
